import { create, type StateCreator } from 'zustand';
import { devtools, persist } from 'zustand/middleware';

import type { IUser } from '@/types/api';

interface IUserState {
    token: string;
    userInfo: IUser.UserItem;
    collapsed: boolean;
    isDark: boolean;
    updateToken: (token: string) => void;
    updateUserInfo: (userInfo: IUser.UserItem) => void;
    updateCollapsed: () => void;
    updateTheme: (isDark: boolean) => void;
}

export const initUserInfo = {
    createId: '',
    createTime: '',
    deptId: '',
    deptName: '',
    gender: '',
    job: '',
    lastLoginTime: '',
    mobile: '',
    roleList: [],
    state: '',
    userEmail: '',
    userId: '',
    userImg: '',
    userName: ''
};

const useUserStore = create<IUserState>(
    devtools(
        persist(
            (set) => ({
                token: '',
                userInfo: initUserInfo,
                collapsed: false,
                isDark: false,
                updateToken(token) {
                    set({ token });
                },
                updateUserInfo(userInfo) {
                    set({ userInfo });
                },
                updateCollapsed() {
                    set((state) => {
                        return {
                            collapsed: !state.collapsed
                        };
                    });
                },
                updateTheme: (isDark) => set({ isDark })
            }),
            {
                // 本地存储的 key
                name: 'user-store',
                // 只持久化 token 和 isDark，其他状态不持久化
                partialize: (state) => ({
                    token: state.token,
                    isDark: state.isDark
                }),
                // 推荐用原生 localStorage 或专门的 string 适配器
                storage: {
                    getItem: (name) => {
                        const item = localStorage.getItem(name);
                        return item ? JSON.parse(item) : null;
                    },
                    setItem: (name, value) => {
                        localStorage.setItem(name, JSON.stringify(value));
                    },
                    removeItem: (name) => {
                        localStorage.removeItem(name);
                    }
                }
            }
        )
    ) as StateCreator<IUserState, [], []>
);
export default useUserStore;
